package com.deer.wms.inventory.web;

import cn.hutool.core.date.DateUtil;
import com.deer.wms.intercept.annotation.User;
import com.deer.wms.intercept.common.data.CurrentUser;
import com.deer.wms.inventory.constant.InventoryConstant;
import com.deer.wms.inventory.model.Inventory.Inventory;
import com.deer.wms.inventory.model.Inventory.InventoryTransact;
import com.deer.wms.inventory.model.freeze.*;
import com.deer.wms.inventory.service.FreezeDetailService;
import com.deer.wms.inventory.service.FreezeMasterService;
import com.deer.wms.inventory.service.InventoryService;
import com.deer.wms.inventory.service.InventoryTransactService;
import com.deer.wms.project.root.core.result.CommonCode;
import com.deer.wms.project.root.core.result.Result;
import com.deer.wms.project.root.core.result.ResultGenerator;
import com.deer.wms.project.root.exception.ServiceException;
import com.deer.wms.project.root.util.BeanUtils;
import com.deer.wms.project.root.util.DateUtils;
import com.deer.wms.review.manage.model.BillRecord;
import com.deer.wms.review.manage.service.BillRecordService;
import com.deer.wms.review.manage.service.CaseMasterService;
import com.deer.wms.system.manage.model.DataDictDetail;
import com.deer.wms.system.manage.service.DataDictDetailService;
import com.deer.wms.system.manage.service.ValidatorService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.List;

/**
* Created by guo on 2019/12/25.
*/
@Api(description = "冻结Master api接口")
@RestController
@RequestMapping("/freeze/masters")
public class FreezeMasterController {

    @Autowired
    private FreezeMasterService freezeMasterService;

    @Autowired
    private FreezeDetailService freezeDetailService;

    @Autowired
    private CaseMasterService caseMasterService;

    @Autowired
    private InventoryService inventoryService;

    @Autowired
    private ValidatorService validatorService;

    @Autowired
    private BillRecordService billRecordService;

    @Autowired
    private InventoryTransactService inventoryTransactService;

    @Autowired
    private DataDictDetailService dataDictDetailService;


    @ApiOperation(value = "新增freezeMaster以及freezeDetail列表", notes = "新增freezeMaster以及freezeDetail列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/insert")
    public Result add(@RequestBody InsertData insertData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        //Step1.整理数据
        Integer state = 1;
        FreezeMaster freezeMaster = insertData.getFreezeMaster();
        String tableName = "freeze_master";
        Integer nextId = validatorService.getNextId(tableName);

        String billNo = "DJ" + "-" + nextId;
        Integer createUserId = currentUser.getUserId();
        String createUserName = currentUser.getUserName();
        String createTime = DateUtils.getNowDateTimeString();
//        String freezeDescribe = freezeMaster.getFreezeDescribe();
//        DataDictDetail dataDictDetail = dataDictDetailService.getOneByField("dict_key", freezeDescribe);
//        String dictValue = dataDictDetail.getDictValue();
//        if(true) {throw new ServiceException(CommonCode.SERVER_INERNAL_ERROR);}
        //草稿
//        if (insertData.getInsertType() == -2) {
//            state = 2;
//        } else if (insertData.getInsertType() == 0) {
//            String billNo1 = insertData.getFreezeMaster().getBillNo();
//            //通过草稿提交，则需要先把草稿删掉
//            if (billNo1 != null) {
//                freezeMasterService.deleteByBillNo(billNo1);
//            }
            //审核 -1不通过  0-流转中 1-已通过
//            state = caseMasterService.createCase(billNo, 4, currentUser.getUserId(), freezeMaster.getWareId(),freezeMaster.getOrganizationId());
//            if(state==1){
//            }
//        }

        //Step2.主表
        freezeMaster.setBillNo(billNo);
        freezeMaster.setCreateTime(createTime);
        freezeMaster.setCreateUseId(createUserId);
        freezeMaster.setCreateUseName(createUserName);
        freezeMaster.setState(state);
        freezeMaster.setInsertType(insertData.getInsertType());
        freezeMasterService.save(freezeMaster);

        //Step3.明细
        List<FreezeDetail> freezeDetails = insertData.getFreezeDetails();
        for (int i = 0; i < freezeDetails.size(); i++) {
            String detailNo = billNo + "-" + (i + 1);
            FreezeDetail freezeDetail = freezeDetails.get(i);
            freezeDetail.setDetailNo(detailNo);
            freezeDetail.setCreateTime(createTime);
            freezeDetail.setBillNo(billNo);
            freezeDetail.setCreateUseId(currentUser.getUserId());
            freezeDetail.setCreateUseName(currentUser.getUserName());

            Inventory inventory = inventoryService.getById(freezeDetail.getInventoryId());
            freezeDetail.setInventoryId(inventory.getInventoryId());
            if (freezeDetail.getFreezeQuantity() <= (inventory.getQuantity() - inventory.getFreezeQuantity())) {
                freezeDetail.setFreezeQuantity(freezeDetail.getFreezeQuantity());
            } else {
                throw new ServiceException(CommonCode.FREEZE_ERROR, "冻结数量大于库存余量");
            }
            if (insertData.getInsertType() == -2) {
                freezeDetail.setState(0);
            } else if (insertData.getInsertType() == 0) {
                freezeDetail.setState(1);
            }
            freezeDetailService.save(freezeDetail);
            if (state == 1) {
                //添加事务
                InventoryTransact inventoryTransact = this.handleInvTract(freezeDetail, inventory, currentUser, true);
                inventoryTransactService.run(inventoryTransact);
            }
        }
        return ResultGenerator.genSuccessResult();
    }

    private InventoryTransact handleInvTract(FreezeDetail freezeDetail, Inventory inventory, CurrentUser currentUser, boolean flag) {
        InventoryTransact inventoryTransact = new InventoryTransact();
        //Step1.准备数据
        inventoryTransact.setFromInventoryId(freezeDetail.getInventoryId());
        //仓库
        inventoryTransact.setWareId(286);
        inventoryTransact.setWareName("卓品仓库");
        //库位
        inventoryTransact.setFromCellCode(inventory.getCellCode());
        //容器
        inventoryTransact.setFromBoxCode(inventory.getBoxCode());
        //物料
        inventoryTransact.setItemCode(inventory.getItemCode());
        inventoryTransact.setItemName(inventory.getItemName());
        //批次
        inventoryTransact.setFromBatchName(inventory.getBatchName());
        //数量
        inventoryTransact.setFromQuantity(freezeDetail.getFreezeQuantity());
        //包装 转换率
        inventoryTransact.setFromPackDetailId(freezeDetail.getPackDetailId());
        inventoryTransact.setToPackDetailId(freezeDetail.getPackDetailId());
        inventoryTransact.setToTransRatio(1.0);
        inventoryTransact.setFromTransRatio(1.0);
        //创建人 时间
        inventoryTransact.setCreateUserId(currentUser.getUserId());
        inventoryTransact.setCreateUserName(currentUser.getUserName());
        inventoryTransact.setCreateTime(DateUtil.now());
        //事务类型
        if (flag) {
            inventoryTransact.setTransactType(InventoryConstant.INVENTORY_FREEZE);
        }else{
            inventoryTransact.setTransactType(InventoryConstant.INVENTORY_UNFREEZE);
        }

        //来源单据号
        inventoryTransact.setBillNo(freezeDetail.getDetailNo());
        //冻结标识
        //Step2.保存，返回
        inventoryTransactService.save(inventoryTransact);
        return inventoryTransact;
    }



    @ApiOperation(value = "单条释放", notes = "单条释放")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/release")
    public Result release(Integer freezeDetailId, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        FreezeDetail freezeDetail = freezeDetailService.getById(freezeDetailId);
        String billNo = freezeDetail.getBillNo();

        Double quantity = freezeDetail.getFreezeQuantity();
        Inventory inventory = inventoryService.getById(freezeDetail.getInventoryId());
        freezeDetail.setState(2);
//        freezeDetail.setFreezeQuantity(freezeDetail.getFreezeQuantity() - quantity);
        freezeDetailService.updateById(freezeDetail);
        //添加事务

        InventoryTransact inventoryTransact = this.handleInvTract(freezeDetail, inventory, currentUser, false);
        inventoryTransactService.run(inventoryTransact);

        FreezeDetailCriteria criteria = new FreezeDetailCriteria();
        criteria.setBillNo(freezeDetail.getBillNo());
        List<FreezeDetailDto> list = freezeDetailService.findList(criteria);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getState() != 2) {
                return ResultGenerator.genSuccessResult();
            }
        }

        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "整个释放", notes = "整个释放")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/releaseAll")
    public Result releaseAll(String billNo,@ApiIgnore @User CurrentUser currentUser){
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(billNo);
        billRecord.setRecordType(35);//整个释放
        billRecord.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord.setCreateUserId(currentUser.getUserId());
        billRecord.setCreateUserName(currentUser.getUserName());
        billRecordService.createBillRecord(billRecord,currentUser);

        FreezeDetailCriteria criteria =new FreezeDetailCriteria();
        criteria.setBillNo(billNo);
        List<FreezeDetailDto> freezeDetailDtos = freezeDetailService.findList(criteria);
        for(FreezeDetail freezeDetail :freezeDetailDtos){
            Double quantity = freezeDetail.getFreezeQuantity();
            Inventory inventory = inventoryService.getById(freezeDetail.getInventoryId());
            //添加事务
            Inventory toIv = new Inventory();
            BeanUtils.copyProperties(inventory, toIv);
            toIv.setFreezeQuantity(inventory.getFreezeQuantity()-quantity);//库存冻结数量扣减
            toIv.setQuantity(inventory.getQuantity() + quantity); //库存加回
//            inventoryTransactService.run(inventory, toIv, InventoryConstant.INVENTORY_FREEZE, freezeDetail.getDetailNo(), currentUser.getUserId(), currentUser.getUserName(), null);

            freezeDetail.setState(2);
            freezeDetail.setFreezeQuantity(freezeDetail.getFreezeQuantity()-quantity);
        }
        FreezeMaster freezeMaster = freezeMasterService.findBy("bill_no",billNo);
        freezeMaster.setState(2);
        freezeMasterService.updateById(freezeMaster);
        BillRecord billRecord1 =billRecordService.findByBillNoAndType(billNo,35);//整个释放
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord1.setModifyUserId(currentUser.getUserId());
        billRecord1.setModifyUserName(currentUser.getUserName());
        billRecordService.updateById(billRecord1);


        return ResultGenerator.genSuccessResult();
    }



    @ApiOperation(value = "审核", notes = "审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/review")
    public Result review(String billNo, Integer reviewResult,Integer caseDetailId,String memo, @ApiIgnore @User CurrentUser currentUser) {
        FreezeMaster freezeMaster = freezeMasterService.findBy("bill_no", billNo);
        //-1不通过   0-流转中  1-通过  2-初始化
        Integer lastReviewResult = caseMasterService.review(caseDetailId,currentUser.getUserId(),reviewResult,memo);


        if (lastReviewResult == -1) {
            freezeMaster.setState(-1);
            freezeMasterService.updateById(freezeMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,31);//冻结审核
            billRecord.setResult("退回");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        } else if (lastReviewResult == 0) {
            freezeMaster.setState(0);
            freezeMasterService.updateById(freezeMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,31);//冻结审核
            billRecord.setResult("流转");
            billRecordService.updateById(billRecord);
        }else if (lastReviewResult == 2) {
            freezeMaster.setState(2);
            freezeMasterService.updateById(freezeMaster);
        } else if (lastReviewResult == 1) {
            freezeMaster.setState(1);
            freezeMasterService.updateById(freezeMaster);
            BillRecord billRecord = billRecordService.findByBillNoAndType(billNo,31);//冻结审核
            billRecord.setResult("通过");
            billRecord.setModifyTime(DateUtils.getNowDateTimeString());
            billRecord.setModifyUserId(currentUser.getUserId());
            billRecord.setModifyUserName(currentUser.getUserName());
            billRecordService.updateById(billRecord);
        }
        if(freezeMaster.getState() ==1){
            FreezeDetailCriteria criteria = new FreezeDetailCriteria();
            criteria.setBillNo(billNo);
            List<FreezeDetailDto> freezeDetails = freezeDetailService.findList(criteria);
            for(FreezeDetail freezeDetail :freezeDetails){
                Inventory inventory = inventoryService.getById(freezeDetail.getInventoryId());
                inventory.setFreezeQuantity(freezeDetail.getFreezeQuantity());
                if(freezeDetail.getFreezeQuantity().equals(inventory.getQuantity())){
                    inventory.setState(2); //全部冻结
                }else {
                    inventory.setState(1);  //部分冻结
                }
                inventoryService.updateById(inventory);
            }

        }

        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "重新发起审核", notes = "重新发起审核")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @GetMapping("/reReview")
    public Result reReview(String billNo, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        FreezeMaster freezeMaster = freezeMasterService.findBy("bill_no", billNo);

        //初始化状态 2
        freezeMaster.setState(2);
        freezeMasterService.updateById(freezeMaster);
        caseMasterService.createCase(billNo, 4, currentUser.getUserId(), freezeMaster.getWareId(),freezeMaster.getOrganizationId());

        return ResultGenerator.genSuccessResult();
    }





    @GetMapping("/delete")
    public Result delete(Integer id) {
        freezeMasterService.removeById(id);
        return ResultGenerator.genSuccessResult();
    }


    @ApiOperation(value = "增删detail", notes = "增删detail")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "access-token", value = "token", paramType = "header", dataType = "String", dataTypeClass = String.class,  required = true)
    })
    @PostMapping("/update")
    public Result update(@RequestBody InsertData insertData, @ApiIgnore @User CurrentUser currentUser) {
        if (currentUser == null) {
            return ResultGenerator.genFailResult(CommonCode.MISSING_PERMISSION_PARAMTER, null);
        }
        BillRecord billRecord =new BillRecord();
        billRecord.setBillNo(insertData.getFreezeMaster().getBillNo());
        billRecord.setRecordType(33);//冻结修改
        billRecord.setCreateTime(DateUtils.getNowDateTimeString());
        billRecord.setCreateUserId(currentUser.getUserId());
        billRecord.setCreateUserName(currentUser.getUserName());
        billRecordService.createBillRecord(billRecord,currentUser);

        freezeDetailService.deleteByBillNo(insertData.getFreezeMaster().getBillNo());
        List<FreezeDetail> freezeDetails = insertData.getFreezeDetails();
        for (int i = 0;i<freezeDetails.size();i++){
            FreezeDetail freezeDetail = freezeDetails.get(i);
            String detailNo = insertData.getFreezeMaster().getBillNo() + "-" + (i+1);
            freezeDetail.setDetailNo(detailNo);
            freezeDetail.setCreateTime(insertData.getFreezeMaster().getCreateTime());
            freezeDetail.setBillNo(insertData.getFreezeMaster().getBillNo());
            freezeDetail.setDetailNo(detailNo);
            freezeDetail.setCreateUseId(insertData.getFreezeMaster().getCreateUseId());
            freezeDetail.setCreateUseName(insertData.getFreezeMaster().getCreateUseName());
            Inventory inventory = inventoryService.getById(freezeDetail.getInventoryId());
            if(freezeDetail.getFreezeQuantity()<(inventory.getQuantity()-inventory.getFreezeQuantity())){
                freezeDetail.setFreezeQuantity(freezeDetail.getFreezeQuantity());
            }else {
                throw new ServiceException(CommonCode.FREEZE_ERROR, "冻结数量大于库存余量");
            }

            if(insertData.getInsertType() ==-2){
                freezeDetail.setState(0);
            }else if(insertData.getInsertType() ==0){
                freezeDetail.setState(1);
            }
            freezeDetailService.save(freezeDetail);
        }
        BillRecord billRecord1 =billRecordService.findByBillNoAndType(insertData.getFreezeMaster().getBillNo(),33);//冻结修改;
        billRecord1.setModifyTime(DateUtils.getNowDateTimeString());
        billRecord1.setModifyUserId(currentUser.getUserId());
        billRecord1.setModifyUserName(currentUser.getUserName());
        billRecordService.updateById(billRecord1);
        return ResultGenerator.genSuccessResult();
    }

    @GetMapping("/detail")
    public Result detail(@PathVariable Integer id) {
        FreezeMaster freezeMaster = freezeMasterService.getById(id);
        return ResultGenerator.genSuccessResult(freezeMaster);
    }

    @GetMapping("/list")
    public Result list(FreezeMasterCriteria criteria) {
        PageHelper.startPage(criteria.getPageNum(), criteria.getPageSize());
        List<FreezeMasterDto> list = freezeMasterService.findList(criteria);
        PageInfo pageInfo = new PageInfo(list);
        return ResultGenerator.genSuccessResult(pageInfo);
    }

}
